import { NextRequest, NextResponse } from 'next/server';
import axios from 'axios';

export async function GET(request: NextRequest) {
  try {
    const url = new URL(request.url || 'http://localhost');
    const contractAddress = url.searchParams.get('contractAddress');
    const chain = url.searchParams.get('chain');

    if (!contractAddress || !chain) {
      return NextResponse.json({ error: '缺少必要参数' }, { status: 400 });
    }

    // 获取实时价格
    const response = await axios.get(
      `https://api.dexscreener.com/latest/dex/tokens/${contractAddress}`,
      {
        timeout: 5000,
        headers: {
          'User-Agent': 'MemeBot/1.0',
          'Accept': 'application/json'
        }
      }
    );

    if (response.data && response.data.pairs && response.data.pairs.length > 0) {
      const chainMap: { [key: string]: string } = {
        'SOLANA': 'solana',
        'BSC': 'bsc', 
        'BASE': 'base'
      };

      let pair = response.data.pairs.find((p: any) => 
        p.chainId === chainMap[chain.toUpperCase()]
      );
      
      if (!pair) {
        pair = response.data.pairs.reduce((best: any, current: any) => {
          const currentLiquidity = current.liquidity?.usd || 0;
          const bestLiquidity = best?.liquidity?.usd || 0;
          return currentLiquidity > bestLiquidity ? current : best;
        }, response.data.pairs[0]);
      }

      if (pair && pair.priceUsd) {
        const price = parseFloat(pair.priceUsd);
        return NextResponse.json({ 
          price,
          timestamp: new Date().toISOString()
        });
      }
    }

    return NextResponse.json({ error: '无法获取价格' }, { status: 404 });

  } catch (error) {
    console.error('获取当前价格失败:', error);
    return NextResponse.json(
      { error: '获取当前价格失败' },
      { status: 500 }
    );
  }
}
